package controller;

import model.Log;
import model.LogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2023-12-08
 * Time：19:25
 */
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        if (session == null) {
            resp.sendRedirect("login.html");
            return;
        }

        User user = (User) session.getAttribute("user");
        if (user == null) {
            System.out.println("该用户未登陆");
            return;
        }
        int userId = user.getUserId();

        session.removeAttribute("user");
        session.removeAttribute("admin");
        resp.sendRedirect("login.html");

        //输出日志
        Log log = new Log();
        log.setUserId(userId);
        log.setAction("该用户登出博客系统成功！");
        LogDao logDao = new LogDao();
        logDao.insert(log);
    }
}
